﻿//--------------------- Copyright Block ----------------------
/*


C# Code By: Tareq Ateik

License: GNU General Public License, ver 3

TERMS OF USE:
	Permission is granted to use this code, with or
	without modification, in any website or application
	provided that credit is given to the original work
	with a link back to ateik.me

This program is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY.

PLEASE DO NOT REMOVE THIS COPYRIGHT BLOCK.

*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using System.IO.IsolatedStorage;
using System.Xml.Linq;

namespace PrayerTime
{
    public partial class MainPage : PhoneApplicationPage
    {
        #region
        GeoCoordinateWatcher Watcher;
        double Lng, Lat;
        PrayerSettings PrayerSettings;
        WebClient wc = new WebClient();
        WebClient GeocodingWebClient = new WebClient();
        const string ReverseGeocoding = "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false";
        #endregion
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            // set Gregorian and Hijri Dates
            Englishtxt.Text = DateTime.Now.ToString("MMMM d, yyyy");
            Hijritxt.Text = Hijri.GreToHij(DateTime.Now).ToShortDateString();
            var z =TimeZoneInfo.Utc.BaseUtcOffset;
            if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue("PrayerSettings", out PrayerSettings) || PrayerSettings== null||PrayerSettings.CurrentLocation == null)
            {
                // Default settings
                PrayerSettings = new PrayerSettings();
                PrayerSettings.CurrentCity = "";
                PrayerSettings.UseGPS = false;
                PrayerSettings.CalculationMethod = CalcuationMethod.Makkah;
                PrayerSettings.AsrMethod = AsrMethod.Shafii;
                if (Watcher == null)
                {
                    Watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                    Watcher.MovementThreshold = 20;
                    Watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(Watcher_StatusChanged);
                }
                Watcher.Start();
                progressBar.IsIndeterminate = true;
                progressBar.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                Lat = PrayerSettings.CurrentLocation.Latitude;
                Lng = PrayerSettings.CurrentLocation.Longitude;
                PageTitle.Text = String.IsNullOrEmpty(PrayerSettings.CurrentCity)? "Prayer Time" : PrayerSettings.CurrentCity;
                SetPrayers(PrayerSettings.CurrentLocation);
                (Application.Current as App).PrayerSettings = PrayerSettings;
            }
        }
        void Watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            GeoCoordinate co = null;
            if (e.Status == GeoPositionStatus.Ready)
            {
                co = Watcher.Position.Location;
                Lat = co.Latitude;
                Lng = co.Longitude;
                // After Getting the latitude and longitude of the Device (we dont want to use this, we will ask for the Lng&Lat of the city)
                // we look for the name of the city (Reverse Geocoding), (Lat,Lng) => name of the place
                wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
                wc.DownloadStringAsync(new Uri(String.Format(ReverseGeocoding,Lat,Lng)));
                Watcher.Stop();
            }
        }
        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            XDocument document = XDocument.Parse(e.Result);

            var data = (from query in document.Descendants("result")
                        select new ReverseGeocodingResults()
                        {
                            Dummy = (string)query.Element("type"),
                            Type = (string)query.Element("type"),
                            City = (string)query.Element("formatted_address")
                        }).Distinct();
            List<ReverseGeocodingResults> list = data.ToList<ReverseGeocodingResults>();

            foreach (ReverseGeocodingResults r in list)
            {
                if (r.Type == "administrative_area_level_1")
                {
                    // Getting the Lng & Lat of the city (Geocoding)
                    GeocodingWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GeocodingWebClient_DownloadStringCompleted);
                    GeocodingWebClient.DownloadStringAsync(new Uri("http://maps.googleapis.com/maps/api/geocode/xml?address=" + r.City + "&sensor=false&language=en"));
                    PrayerSettings.CurrentCity = r.City;
                    PageTitle.Text = r.City;
                    break;
                }
            }

        }
        void GeocodingWebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            XDocument document = XDocument.Parse(e.Result);

            var data = (from query in document.Descendants("result")
                        select new ResearchResult()
                        {
                            Location = new GeoCoordinate((double)query.Element("geometry").Element("location").Element("lat"), (double)query.Element("geometry").Element("location").Element("lng")),
                            City = (string)query.Element("formatted_address")
                        }).FirstOrDefault();

            PrayerSettings.CurrentLocation = data.Location;
            SetPrayers(data.Location);
            (Application.Current as App).PrayerSettings = PrayerSettings;
            progressBar.Visibility = System.Windows.Visibility.Collapsed;
            progressBar.IsIndeterminate = false;
        }
        private void SetPrayers(GeoCoordinate point)
        {
            double lon = point.Longitude;
            double lat = point.Latitude;

            PrayerTime prayerTime = new PrayerTime();
            prayerTime.setTimeFormat(0);

            prayerTime.setCalcMethod((int)PrayerSettings.CalculationMethod);
            prayerTime.setAsrMethod((int)PrayerSettings.AsrMethod);
            DateTime today = DateTime.Now;
            var y = TimeZoneInfo.Local.GetUtcOffset(DateTime.Now);
            string[] s = prayerTime.getDatePrayerTimes(today.Year, today.Month, today.Day, lat, lon, y.Hours);

            DateTime[] d = new DateTime[7];

            for (int i = 0; i < d.Length; i++)
                d[i] = DateTime.Parse(s[i]);
            Prayer[] prayers = new Prayer[6];
            prayers[0] = new Prayer { PrayerTitle = "Al Fajr ", PrayerTime = d[0].ToString("hh:mm tt") };
            prayers[1] = new Prayer { PrayerTitle = "Sunrise", PrayerTime = d[1].ToString("hh:mm tt") };
            prayers[2] = new Prayer { PrayerTitle = "Al Duhur", PrayerTime = d[2].ToString("hh:mm tt") };
            prayers[3] = new Prayer { PrayerTitle = "Al Asr", PrayerTime = d[3].ToString("hh:mm tt") };
            prayers[4] = new Prayer { PrayerTitle = "Al Maghreb", PrayerTime = d[4].ToString("hh:mm tt") };
            prayers[5] = new Prayer { PrayerTitle = "Al Eishaa ", PrayerTime = d[6].ToString("hh:mm tt") };

            prayerTimes.ItemsSource = prayers;
        }
        private void PhoneApplicationPage_Unloaded(object sender, RoutedEventArgs e)
        {

        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            IsolatedStorageSettings.ApplicationSettings["PrayerSettings"] = PrayerSettings;
            (Application.Current as App).PrayerSettings = PrayerSettings;

            progressBar.IsIndeterminate = false;
            progressBar.Visibility = System.Windows.Visibility.Collapsed;
            base.OnNavigatedFrom(e);
        }
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        }
        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/FindMosque.xaml", UriKind.Relative));
        }
        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative));
        }
    }
}